import dayjs from 'dayjs'
// 引入字典表
import dictionary from './dictionary'

/**
 * Show plural label if time is plural number
 * @param {number} time
 * @param {string} label
 * @return {string}
 */
function pluralize(time, label) {
  if (time === 1) {
    return time + label
  }
  return time + label + 's'
}

/**
 * @param {number} time
 */
// 显示时间差
export function timeAgo (value) {
  const
    s = 1000,
    m = 60 * s,
    h = 60 * m,
    d = 24 * h,
    mo = 30 * d,
    y = 365 * d

  const fdate = [
    {
      time: y,
      text: '年'
    }, {
      time: mo,
      text: '月'
    }, {
      time: d,
      text: '天'
    }
  ]
  // 计算出时间差
  const time = Date.now() - new Date(+value)
  for (let i = 0; i < fdate.length; i++) {
    const t = time / fdate[i].time
    if (t >= 1) {
      return Math.floor(t) + fdate[i].text
    }
  }
}


/**
 * Number formatting
 * like 10000 => 10k
 * @param {number} num
 * @param {number} digits
 */
export function numberFormatter(num, digits) {
  const si = [
    { value: 1E18, symbol: 'E' },
    { value: 1E15, symbol: 'P' },
    { value: 1E12, symbol: 'T' },
    { value: 1E9, symbol: 'G' },
    { value: 1E6, symbol: 'M' },
    { value: 1E3, symbol: 'k' }
  ]
  for (let i = 0; i < si.length; i++) {
    if (num >= si[i].value) {
      return (num / si[i].value + 0.1).toFixed(digits).replace(/\.0+$|(\.[0-9]*[1-9])0+$/, '$1') + si[i].symbol
    }
  }
  return num.toString()
}

/**
 * 10000 => "10,000"
 * @param {number} num
 */
export function toThousandFilter(num) {
  return (+num || 0).toString().replace(/^-?\d+/g, m => m.replace(/(?=(?!\b)(\d{3})+$)/g, ','))
}

/**
 * Upper case first char
 * @param {String} string
 */
export function uppercaseFirst(string) {
  return string.charAt(0).toUpperCase() + string.slice(1)
}

/**
 * array to Object
 * @param array
 */
export function displayNameFilter(key, array) {
  for (let i = 0; i < array.length; i++) {
    if (array[i].key === key) {
      return array[i].display_name
    }
  }
}

export function toPersentFilter(val) {
  if (val) {
    return val + '%'
  }
}

// 处理空字段
export function dealNull(val) {
  return val || '-'
}

// 处理时间格式为自定义，如'YYYY-MM-DD' 为2020-06-06，默认为年月日时分秒
export function formatTimestamp(time, format = 'YYYY-MM-DD hh:mm:ss') {
  if (time && /^[0-9]+.?[0-9]*/.test(time)) {
    return dayjs(+time).format(format)
  } else {
    return time
  }
}

// 处理字典表
export function formatDictionary(val, list) {
  if (val === null || val === '') {
    return '-'
  }
  const result = list.find(item => +item.code == +val)
  return result ? result.name : '-'
}

// 处理行业
export function formatHY(val, list) {
  if (val === null || val === '') {
    return '-'
  }
  const result = list.find(item => +item.id == +val)
  return result ? result.name : '-'
}
